package com.leetcode;

/**
 * @author yijy
 * @description
 * 给定两个字符串形式的非负整数 num1 和num2 ，计算它们的和。
 *
 * 提示：
 *
 * num1 和num2 的长度都小于 5100
 * num1 和num2 都只包含数字 0-9
 * num1 和num2 都不包含任何前导零
 * 你不能使用任何內建 BigInteger 库， 也不能直接将输入的字符串转换为整数形式
 * @create 2021/5/7 下午8:09
 **/
public class Solution2 {


    public static void main(String[] args) {
        Solution2 solution2 = new Solution2();
        System.out.println(solution2.sum("123","399"));
        System.out.println(solution2.sumAsc("623","399"));
        System.out.println(solution2.sumAndInt(623,399));
    }

    private String sum(String num1, String num2) {
        long l1 = num1.length();
        long l2 = num2.length();
        StringBuffer sb = new StringBuffer();
        int carry = 0;
        int i=0;
        while ( i<l1 || i<l2 || carry >0) {
            int a = i<l1 ? Integer.valueOf(String.valueOf(num1.charAt(i))) : 0;
            int b = i<l2 ? Integer.valueOf(String.valueOf(num2.charAt(i))) : 0;
            int sum = carry + a + b;
            carry = sum/10;
            sb.append(sum%10);
            i++;
        }
        return sb.toString();
    }

    private String sumAsc(String num1, String num2) {
        int l1 = num1.length();
        int l2 = num2.length();
        String result = "";
        int carry = 0;
        int i= l1 >l2 ? l1-1 : l2-1;
        while ( i>=0 || carry >0) {
            int a = 0;
            if(0<=i && i<l1){
                a = Integer.valueOf(String.valueOf(num1.charAt(i)));
            }
            int b = 0;
            if(0<=i && i<l2){
                b = Integer.valueOf(String.valueOf(num2.charAt(i)));
            }
            int sum = carry + a + b;
            carry = sum/10;
            result= sum%10 + result;
            i--;
        }
        return result;
    }

    private String sumAndInt(int n1, int n2) {
        String num1 = String.valueOf(n1);
        String num2 = String.valueOf(n2);
        int l1 = num1.length();
        int l2 = num2.length();
        String result = "";
        int carry = 0;
        int i= l1 >l2 ? l1-1 : l2-1;
        while ( i>=0 || carry >0) {
            int a = 0;
            if(0<=i && i<l1){
                a = Integer.valueOf(String.valueOf(num1.charAt(i)));
            }
            int b = 0;
            if(0<=i && i<l2){
                b = Integer.valueOf(String.valueOf(num2.charAt(i)));
            }
            int sum = carry + a + b;
            carry = sum/10;
            result= sum%10 + result;
            i--;
        }
        return result;
    }





}
